package com.zhejiangzhengyuan.municipal_flooded_road.controller;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPath;
import com.zhejiangzhengyuan.municipal_common.entity.LED.JsonBean;
import com.zhejiangzhengyuan.municipal_common.entity.LED.SendTextJson;
import com.zhejiangzhengyuan.municipal_common.response.ResponseVo;
import com.zhejiangzhengyuan.municipal_common.service.LedHistoryService;
import com.zhejiangzhengyuan.municipal_common.utils.ConstantUtil;
import com.zhejiangzhengyuan.municipal_common.utils.LED.DeviceUtils;
import com.zhejiangzhengyuan.municipal_common.utils.LED.HeartBeatUtils;
import com.zhejiangzhengyuan.municipal_common.utils.LED.URLUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;
import java.util.Map;

@Api(tags = "物联网设备管理模块")
@RestController
@RequestMapping("/ponding/deviceIot")
@Slf4j
public class FloodRoadDeviceController {

  @Autowired private URLUtils urlUtils;

  @Autowired private SendTextJson sendTextJson;

  @Autowired private LedHistoryService ledHistoryService;

  /**
   * 获取设备的信息
   *
   * @return
   * @throws IOException
   */
  @ApiOperation("获取设备的信息")
  @RequestMapping(value = "/getDeviceInformationList", method = RequestMethod.GET)
  public ResponseVo getDeviceInformationList() throws IOException {
    Document document = Jsoup.connect(urlUtils.GetDeviceMainURL()).get();
    List<Map<String, String>> mapList = DeviceUtils.GetDeviceData(document);
    return new ResponseVo<>(ConstantUtil.ResultCode.SUCCESS, mapList);
  }

  /**
   * 设备心跳数据
   *
   * @return
   * @throws IOException
   */
  @ApiOperation("设备心跳数据")
  @RequestMapping(value = "/getHeartBeatList", method = RequestMethod.GET)
  public ResponseVo getHeartBeatList() throws IOException {
    Document document = Jsoup.connect(urlUtils.GetHeartBeatURL()).get();
    List<Map<String, String>> strMap = HeartBeatUtils.GetHeartBeatData(document);
    return new ResponseVo<>(ConstantUtil.ResultCode.SUCCESS, strMap);
  }

  /**
   * 下发节目
   *
   * @return
   */
  @ApiOperation("下发节目")
  @RequestMapping(
      value = "/sendData",
      method = RequestMethod.POST,
      produces = "application/json; charset=utf-8")
  public ResponseVo sendData(String deviceCode, @RequestBody JsonBean jsonBean) {
    JSONObject assignments = assignments(jsonBean);
    log.info("下发节目 : " + assignments);
    return ledHistoryService.sendLedData(deviceCode, assignments) == HttpStatus.SC_OK
        ? new ResponseVo<>(ConstantUtil.ResultCode.SUCCESS)
        : new ResponseVo<>(ConstantUtil.ResultCode.SERVER_ERROR);
  }

  public JSONObject assignments(JsonBean jsonBean) {
    log.info(">>>: " + jsonBean);
    JSONObject requestData = sendTextJson.senText;
    JSONPath.set(requestData, "$page[0].areaList.mediaEle[0].fontFamily", jsonBean.getFontFamily());
    JSONPath.set(requestData, "$page[0].areaList.mediaEle[0].fontSize", jsonBean.getFontSize());
    JSONPath.set(requestData, "$page[0].areaList.mediaEle[0].lineHeight", jsonBean.getLineHeight());
    JSONPath.set(requestData, "$page[0].areaList.mediaEle[0].fontColor", jsonBean.getFontColor());
    JSONPath.set(requestData, "$page[0].areaList.mediaEle[0].fontWeight", jsonBean.getFontWeight());
    JSONPath.set(requestData, "$page[0].areaList.mediaEle[0].siderType", jsonBean.getSiderType());
    JSONPath.set(requestData, "$page[0].areaList.mediaEle[0].pauseTime", jsonBean.getPauseTime());
    JSONPath.set(
        requestData, "$page[0].areaList.mediaEle[0].scrollSpeed", jsonBean.getScrollSpeed());
    JSONPath.set(
        requestData,
        "$page[0].areaList.mediaEle[0].textGroup[0].text",
        removeBlankSpace(jsonBean.getText()));
    return requestData;
  }

  private Object removeBlankSpace(String text) {
    if (text != null) {
      log.info("返回数据前: " + text);
      String s1 = text.replace("&nbsp;", " "); // todo 先剔除空格
      String s2 = s1.replace("<div><br></div>", " "); // todo  再剔除回车
      log.info("返回数据后: " + s2);
      return s2;
    }
    return "";
  }

  //    @RequestMapping(value = "/getTest",method = RequestMethod.GET)
  //    public void ScheduleTimeHack() throws IOException, InterruptedException {
  //
  //        log.info("道路积水系统开始定时重启,现在时间是:" + LocalDateTime.now());
  //        Document document = Jsoup.connect(urlUtils.GetDeviceMainURL()).get();//todo 得到在线的设备
  //        List<Map<String, String>> mapList = DeviceUtils.GetDeviceData(document);
  //        for (Map<String, String> map : mapList) {
  //            String mac = map.get("MAC");
  //            String deviceCode = map.get("DeviceCode");
  //            Thread.sleep(10000); //todo 延迟10秒
  //            TimeHack(deviceCode); //todo 开启异步
  //        }
  //    }
  //
  //    @Async
  //    public void TimeHack(String deviceCode) {
  //        log.info("LED显示屏 设备编号为：" + deviceCode + " 准备对时！");
  //        Map<String, String> map = new HashMap<>();
  //        map.put("devCode", deviceCode);
  //        map.put("content", "");
  //        map.put("type", "80");//todo 80指令为同步时钟
  //        HttpClientUtils.doPost(urlUtils.GetSendTaskURL(),map);
  //    }

}
